import type { Theme, SxProps } from '@mui/material/styles';

import { varAlpha } from 'minimal-shared/utils';
import { useRef, useState, useEffect, useCallback } from 'react';

import Box from '@mui/material/Box';
import { useTheme } from '@mui/material/styles';
import ButtonBase from '@mui/material/ButtonBase';
import IconButton from '@mui/material/IconButton';

import { usePathname } from 'src/routes/hooks';
import { RouterLink } from 'src/routes/components';

import { Iconify } from 'src/components/iconify';

import type { NavItem } from '../nav-config-dashboard';

/**
 * TopNav 顶部导航组件：用于渲染一级菜单，并根据当前路径高亮。
 * - 当某个一级菜单没有设置 `path` 时，会回退到其第一个子项的路径。
 * - 点击一级菜单会导航到相应路径，并在左侧显示其二级菜单。
 */
export type TopNavProps = {
  data: NavItem[];
  sx?: SxProps<Theme>;
};

/**
 * 递归查找第一个可用的路径，用于没有设置 `path` 的分组型导航项。
 */
function resolveItemHref(item: NavItem): string | undefined {
  if (item.path) return item.path;
  if (item.children && item.children.length > 0) {
    for (const child of item.children) {
      const href = resolveItemHref(child);
      if (href) return href;
    }
  }
  return undefined;
}

/**
 * 递归判断某个导航项（及其子项）是否与当前路径匹配。
 */
function matchPathRecursive(node: NavItem, pathname: string): boolean {
  if (node.path && node.path === pathname) return true;
  if (node.children && node.children.length > 0) {
    return node.children.some((child) => matchPathRecursive(child, pathname));
  }
  return false;
}

/**
 * 顶部导航主组件：水平排列一级菜单项，支持图标与标题，并根据当前路径高亮。
 */
export function TopNav({ data = [], sx }: TopNavProps) {
  const theme = useTheme();
  const pathname = usePathname();
  const trackRef = useRef<HTMLDivElement | null>(null);
  const [canScrollLeft, setCanScrollLeft] = useState(false);
  const [canScrollRight, setCanScrollRight] = useState(false);

  /**
   * 更新左右箭头显示状态：根据滚动位置与内容宽度判断是否可向左/向右滚动。
   */
  const updateScrollState = useCallback(() => {
    const el = trackRef.current;
    if (!el) return;
    const { scrollLeft, scrollWidth, clientWidth } = el;
    setCanScrollLeft(scrollLeft > 0);
    setCanScrollRight(scrollLeft + clientWidth < scrollWidth - 1);
  }, []);

  /**
   * 处理向左滚动：每次滚动一个固定距离，带平滑动画。
   */
  const handleScrollLeft = useCallback(() => {
    const el = trackRef.current;
    if (!el) return;
    el.scrollBy({ left: -240, behavior: 'smooth' });
  }, []);

  /**
   * 处理向右滚动：每次滚动一个固定距离，带平滑动画。
   */
  const handleScrollRight = useCallback(() => {
    const el = trackRef.current;
    if (!el) return;
    el.scrollBy({ left: 240, behavior: 'smooth' });
  }, []);

  /**
   * 初始化与监听：在挂载后、窗口尺寸变化以及滚动时更新箭头状态。
   */
  useEffect(() => {
    updateScrollState();
    const el = trackRef.current;
    if (!el) return () => { };

    const handleScroll = () => updateScrollState();
    el.addEventListener('scroll', handleScroll, { passive: true });

    const RO = (window as any).ResizeObserver;
    const ro = RO ? new RO(() => updateScrollState()) : null;
    if (ro) ro.observe(el);

    const handleWindowResize = () => updateScrollState();
    window.addEventListener('resize', handleWindowResize);

    return () => {
      el.removeEventListener('scroll', handleScroll);
      window.removeEventListener('resize', handleWindowResize);
      if (ro) ro.disconnect();
    };
  }, [updateScrollState]);

  useEffect(() => {
    updateScrollState();
  }, [data, updateScrollState]);

  return (
    <Box
      component="nav"
      sx={[
        {
          position: 'relative',
          display: 'flex',
          alignItems: 'center',
        },
        ...(Array.isArray(sx) ? sx : [sx]),
      ]}
    >
      <Box
        ref={trackRef}
        sx={{
          gap: 6,
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'start',
          overflowX: 'auto',
          scrollbarWidth: 'none',
          '&::-webkit-scrollbar': { display: 'none' },
          px: 1,
        }}
      >
        {data.map((item) => {
          const isActive =
            (!!item.path && item.path === pathname) ||
            (item.children && item.children.length > 0
              ? item.children.some((child) => matchPathRecursive(child, pathname))
              : false);

          const href = resolveItemHref(item);
          const Component: React.ElementType = href ? RouterLink : 'div';

          return (
            <ButtonBase
              key={item.title}
              component={Component}
              href={href}
              sx={{
                px: 1.5,
                py: 1,
                gap: 1,
                borderRadius: 1,
                fontWeight: 'bolder',
                lineHeight: '17px',
                display: 'flex',
                alignItems: 'center',
                color: isActive ? theme.vars.palette.primary.main : theme.vars.palette.text.secondary,
                ...(isActive && {
                  bgcolor: varAlpha(theme.vars.palette.primary.mainChannel, 0.08),
                  '&:hover': {
                    bgcolor: varAlpha(theme.vars.palette.primary.mainChannel, 0.16),
                  },
                }),
                flexShrink: 0,
              }}
            >
              {/* <Box component="span" sx={{ width: 20, height: 20 }}>
                {item.icon}
              </Box>
              <Box component="span" sx={{ typography: 'subtitle2' }}>
                {item.title}
              </Box> */}
              <div>
                {item.icon}
              </div>
              <div>
                {item.title}
              </div>
            </ButtonBase>
          );
        })}
      </Box>

      {canScrollLeft && (
        <IconButton
          onClick={handleScrollLeft}
          sx={{
            position: 'absolute',
            left: 0,
            top: '50%',
            transform: 'translateY(-50%)',
            bgcolor: 'background.paper',
            color: 'text.secondary',
            boxShadow: theme.vars.customShadows.z8,
          }}
        >
          {/* 使用已注册的向前图标并旋转 180deg 作为向左箭头，避免类型错误 */}
          <Iconify icon="eva:arrow-ios-forward-fill" width={22} sx={{ transform: 'rotate(180deg)' }} />
        </IconButton>
      )}

      {canScrollRight && (
        <IconButton
          onClick={handleScrollRight}
          sx={{
            position: 'absolute',
            right: 0,
            top: '50%',
            transform: 'translateY(-50%)',
            bgcolor: 'background.paper',
            color: 'text.secondary',
            boxShadow: theme.vars.customShadows.z8,
          }}
        >
          <Iconify icon="eva:arrow-ios-forward-fill" width={22} />
        </IconButton>
      )}
    </Box>
  );
}